package com.xjtu.login.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import com.xjtu.login.bean.LoginBean;
import com.xjtu.login.bean.User; 

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request
		.getRequestDispatcher("/WEB-INF/login.jsp")
		.forward(request, response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	   request.setCharacterEncoding("UTF-8");
	   
		User  user = new User();
		Enumeration<String>  enumeration = request.getParameterNames();
		while(enumeration.hasMoreElements()){
		String key = enumeration.nextElement();
		String[] values = request.getParameterValues(key);
		 try {
			BeanUtils.setProperty(user, key, values);
		   } catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		   } 		
		}		
		LoginBean loginBean = new LoginBean();
		boolean flag = loginBean.validate(user);
		if(flag){
			request.getSession().setAttribute("loginBean", loginBean);
			request.getRequestDispatcher("/WEB-INF/success.jsp").forward(request, response);
		}else{
			request.getSession().setAttribute("loginBean", loginBean);
			request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
		}
	}

}
